import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, FlatList, Modal, Image, TextInput, ToastAndroid } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { AntDesign } from '@expo/vector-icons';
import { getDraft, publish } from '../api/draft';
import { useAuth } from '../context/AuthProvider';

const Draft = ({navigation}) => {
	const { user } = useAuth();
	const [page,setPage] = useState(1);
	const [newsList,setNewsList] = useState([]);
	const [refreshing,setRefreshing] = useState(false);
	const [showModal,setShowModal] = useState(false);
	const [draftTitle,setDraftTitle] = useState('');
	const [draftContext,setDraftContext] = useState('');

	useFocusEffect(
		React.useCallback(() => {
			getDraft({page,size:10})
			.then(res => {
				if(page == 1) {
					setNewsList(res.data.content)
				}else{
					setNewsList([...newsList,...res.data.content])
				}
				
				setRefreshing(false)
			})

			navigation.navigate('Draft',{setShowModal})
		},[])
	)

	useFocusEffect(
		React.useCallback(() => {
			getDraft({page,size:10})
			.then(res => {
				if(page == 1) {
					setNewsList(res.data.content)
				}else{
					setNewsList([...newsList,...res.data.content])
				}
				
				setRefreshing(false)
			})

			navigation.navigate('Draft',{setShowModal})
		},[showModal])
	)

	const onEndReached = () => {
		setPage(page+1)
	}
	
	const onRefresh = () => {
		setPage(1)
		setRefreshing(true)
	}

	const handlePublish = () => {
		let data = {draftTitle:draftTitle,draftContext:draftContext,draftUser:user.userId}

		publish(data).then(res => {
			if(res.code === '200') {
				ToastAndroid.show(res.msg,ToastAndroid.SHORT,ToastAndroid.TOP)
				setShowModal(false)
			}
			if(res.code === '500') {
				ToastAndroid.show(`投稿失败！${res.msg}`,ToastAndroid.SHORT,ToastAndroid.TOP)
				setShowModal(false)
			}
		})
	}

	const renderTime = (date) => {
		var dates = new Date(date).toJSON();
		return new Date(+new Date(dates) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') 
	}	  

	return (
		<View style={styles.layout}>
			<Modal 
				animationType="slide"
				transparent={true}
				visible={showModal}
				onRequestClose={() => {
				  setShowModal(!showModal);
				}}
			>
				<View style={{marginTop:150,alignItems:'center',justifyContent:'center',height:300,backgroundColor:'#fff',borderRadius:20}}>
					<TextInput style={{
						width:300,
						height:50,
						margin:10,
						padding:10,
						borderColor:'#777',
						borderWidth:1,
						}} 
						clearTextOnFocus={true}
						placeholder={'投稿标题'}
						onChangeText={text => setDraftTitle(text)}
					/>
					<TextInput style={{
						width:300,
						height:50,
						margin:10,
						padding:10,
						borderColor:'#777',
						borderWidth:1,
						}} 
						clearTextOnFocus={true}
						placeholder={'投稿内容'}
						onChangeText={text => setDraftContext(text)}
					/>
					<View style={{width:300,height:50,margin:10}}>
						<Button title='发布投稿' onPress={handlePublish} />
					</View>
				</View>
			</Modal>

			<FlatList
				data={newsList}
				renderItem={({item}) => 
					<View style={{margin:5,paddingBottom:10,borderBottomWidth:1,borderBottomColor:'#777'}}>
						<View style={{justifyContent:'space-between'}}>
							<Text style={{fontSize:18,lineHeight:30,marginLeft:5}} ellipsizeMode='tail'>{item.draftTitle}</Text>
							<View style={{flexDirection:'row', justifyContent:'space-between'}}>
								<View style={{flexDirection:'row', justifyContent:'flex-start'}}>
									{
										item.user.avatar !== null?
										<Image
											style={{width: 30, height: 30, borderRadius:25}}
											source={{uri: `http://8.142.171.141:8080/school-news/user/img?path=${item.user.avatar}`}}
										/>:<AntDesign name='user' size={24} />
									}
									<Text style={{fontSize:16,lineHeight:26,marginLeft:5}}>{item.user.userName}</Text>
								</View>
								<Text style={{fontSize:14}}>{renderTime(item.draftDate)}</Text>
							</View>
						</View>
					</View>
				}
				keyExtractor={(a)=>a.id}
				onEndReached={onEndReached}
				onRefresh={onRefresh}
				refreshing={refreshing}
			></FlatList>
		</View>
	  );
}

const styles = StyleSheet.create({
	layout:{
	  padding:20
	}
  });

export default Draft;